package com.no1.controller.admin;

import com.no1.dao.AdminDao;
import com.no1.dao.WorkerDao;
import com.no1.dto.Message;
import com.no1.utils.JsonMessage;
import com.no1.utils.StringUtils;
import net.sf.json.util.JSONUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/dologin")
public class LoginController extends javax.servlet.http.HttpServlet {
    private WorkerDao wd = new WorkerDao();

    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        response.setCharacterEncoding("utf-8");
        PrintWriter write = response.getWriter();
        if (!StringUtils.isNullOrEmpty(username) && !StringUtils.isNullOrEmpty(password)) {
            HttpSession session = request.getSession();
            if (wd.login(username, password)) {
                session.setAttribute("user", wd.getWorker(username));
                write.write(JsonMessage.getJsonMessage(1, "登录成功").toString());
            } else {
                write.write(JsonMessage.getJsonMessage(0, "用户名或者密码错误").toString());
            }
        } else {
            write.write(JsonMessage.getJsonMessage(1, "用户名或者密码不能为空").toString());
        }
    }
}
